package com.ecommerce.service;

import com.ecommerce.entity.Product;
import com.ecommerce.entity.Review;
import com.ecommerce.entity.User;
import com.ecommerce.repository.ProductRepository;
import com.ecommerce.repository.ReviewRepository;
import com.ecommerce.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
@Transactional
public class ReviewService {
    
    @Autowired
    private ReviewRepository reviewRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private ProductRepository productRepository;
    
    /**
     * 创建评价
     */
    public Review createReview(Long productId, Long userId, Integer rating, String comment) {
        // 检查用户是否已评价该商品
        Optional<Review> existingReview = reviewRepository.findByProductIdAndUserId(productId, userId);
        if (existingReview.isPresent()) {
            throw new RuntimeException("您已经评价过该商品");
        }
        
        // 验证评分范围
        if (rating < 1 || rating > 5) {
            throw new RuntimeException("评分必须在1-5之间");
        }
        
        // 创建评价
        Review review = new Review();
        review.setRating(rating);
        review.setComment(comment);
        
        // 设置关联关系
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> new RuntimeException("商品不存在"));
        
        review.setUser(user);
        review.setProduct(product);
        
        return reviewRepository.save(review);
    }
    
    /**
     * 获取商品评价列表
     */
    public Page<Review> getProductReviews(Long productId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return reviewRepository.findByProductIdOrderByCreatedAtDesc(productId, pageable);
    }
    
    /**
     * 获取用户评价列表
     */
    public Page<Review> getUserReviews(Long userId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return reviewRepository.findByUserIdOrderByCreatedAtDesc(userId, pageable);
    }
    
    /**
     * 获取商品评价统计信息
     */
    public Map<String, Object> getProductReviewStats(Long productId) {
        Map<String, Object> stats = new HashMap<>();
        
        // 总评价数
        long totalReviews = reviewRepository.countByProductId(productId);
        stats.put("totalReviews", totalReviews);
        
        // 平均评分
        Double averageRating = reviewRepository.getAverageRatingByProductId(productId);
        stats.put("averageRating", averageRating != null ? Math.round(averageRating * 10.0) / 10.0 : 0.0);
        
        // 评分分布
        List<Object[]> ratingDistribution = reviewRepository.getRatingDistributionByProductId(productId);
        Map<Integer, Long> distribution = new HashMap<>();
        for (Object[] row : ratingDistribution) {
            Integer rating = (Integer) row[0];
            Long count = (Long) row[1];
            distribution.put(rating, count);
        }
        stats.put("ratingDistribution", distribution);
        
        return stats;
    }
    
    /**
     * 根据评分筛选评价
     */
    public Page<Review> getProductReviewsByRating(Long productId, Integer minRating, int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        if (minRating != null && minRating > 0) {
            return reviewRepository.findByProductIdAndRatingGreaterThanEqualOrderByCreatedAtDesc(productId, minRating, pageable);
        } else {
            return reviewRepository.findByProductIdOrderByCreatedAtDesc(productId, pageable);
        }
    }
    
    /**
     * 检查用户是否已评价商品
     */
    public boolean hasUserReviewedProduct(Long productId, Long userId) {
        return reviewRepository.findByProductIdAndUserId(productId, userId).isPresent();
    }
    
    /**
     * 删除评价
     */
    public void deleteReview(Long reviewId, Long userId) {
        Optional<Review> reviewOpt = reviewRepository.findById(reviewId);
        if (reviewOpt.isPresent()) {
            Review review = reviewOpt.get();
            if (!review.getUser().getId().equals(userId)) {
                throw new RuntimeException("只能删除自己的评价");
            }
            reviewRepository.delete(review);
        }
    }
} 